package com.zj.leetcode.medium.tree;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @program: algorithm
 * @description: 输出二叉树
 * 655 print-binary-tree
 * 建议略过....
 * @author: Zhang Bo
 * @create: 2022-06-27 10:22:43
 **/
public class PrintBinaryTree {
    public static void main(String[] args) {
        Solution solution = new PrintBinaryTree().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        public List<List<String>> printTree(TreeNode root) {
            int m = depth(root);
            int n = (1 << m) - 1;
            List<List<String>> ans = new ArrayList<>();
            String[][] strs = new String[m][n];
            for (int i = 0; i < m; i++) {
                Arrays.fill(strs[i], "");
            }
            dfs(strs, 0, n, root, 0);
            for (int i = 0; i < m; i++) {
                ans.add(Arrays.asList(strs[i]));
            }
            return ans;
        }

        private void dfs(String[][] strs, int begin, int end, TreeNode root, int level) {
            if (root == null) {
                return;
            }
            int mid = begin + (end - begin) / 2;
            strs[level][mid] = String.valueOf(root.val);
            dfs(strs, begin, mid - 1, root.left, level + 1);
            dfs(strs, mid + 1, end, root.right, level + 1);
        }

        private int depth(TreeNode root) {
            if (root == null) {
                return 0;
            }
            return Math.max(depth(root.left), depth(root.right)) + 1;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}